<?php

namespace App\Http\Resources;

use App\Helpers\BaseResource;

class Category extends BaseResource
{
    /**
     * Transform the resource into an array.
     *
     * @param  \Illuminate\Http\Request $request
     * @return array
     */
    public function toArray($request)
    {
        if ($this->rs_type == 'home') {
            return $this->_getHome();
        }
        if ($this->rs_type == 'mobile-edit') {
            return $this->_getMobileEdit();
        }
        return $this->filterFields(
            [
                'value' => (string)$this->id,
                'label' => $this->name,
                'children' => $this->when(collect($this->children)->count() > 0, function () {
                    return CategoryCollection::make($this->children);
                })
            ]
        );
    }

    protected function _getMobileEdit()
    {
        return [
            'name' => $this->name,
            'value' => (string)$this->id,
            'parent' => (string)($this->parent_id > 0 ? $this->parent_id : '0')
        ];
    }

    protected function _getHome()
    {
        return $this->filterFields(
            [
                'id' => hashid_encode($this->id),
                'title' => $this->name,
                'name' => $this->name,
                'docs' => $this->when($this->ckFields('docs'), function () {
                    return DocCollection::make($this->docs)->hide(['page_count', 'buy_info', 'comment_count', 'subscribe_count'])
                        ->relate(['user' => ['show', 'name']]);
                })
            ]);

    }
}
